﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public static class MyMath
{
    private static float tempRad;
    private static Vector2 tempVector2;

    /// <summary>
    /// 用于摄像机镜头的角色移动转换
    /// </summary>
    /// <param name="direction"></param>
    /// <param name="vector3"></param>
    public static void CameraTransformDirection(Vector3 direction, ref Vector3 vector3)
    {
        tempVector2.Set(direction.x, direction.z);
        tempRad = Mathf.Deg2Rad * Vector2.Angle(Vector2.up, tempVector2);

        if (direction.x < 0)
        {
            tempRad = -tempRad;
        }

        vector3.Set(vector3.x * Mathf.Cos(tempRad) + vector3.z * Mathf.Sin(tempRad),
                    vector3.y,
                    -vector3.x * Mathf.Sin(tempRad) + vector3.z * Mathf.Cos(tempRad));
    }

    /// <summary>
    /// 返回绕某一轴旋转后的方向
    /// </summary>
    /// <param name="direction"></param>
    /// <param name="rotateDirection"></param>
    /// <param name="angle"></param>
    /// <returns></returns>
    public static Vector3 Cycle(Vector3 direction, Vector3 rotateDirection, float angle)
    {
        if (angle == 0)
        {
            return direction;
        }

        float rad = angle * Mathf.Deg2Rad;

        var rotateMatrix = new Matrix4x4();

        rotateMatrix.SetRow(0, new Vector4(Mathf.Cos(rad) + (1 - Mathf.Cos(rad)) * rotateDirection.x * rotateDirection.x, (1 - Mathf.Cos(rad)) * rotateDirection.x * rotateDirection.y - rotateDirection.z * Mathf.Sin(rad), (1 - Mathf.Cos(rad)) * rotateDirection.x * rotateDirection.z + rotateDirection.y * Mathf.Sin(rad), 0));
        rotateMatrix.SetRow(1, new Vector4((1 - Mathf.Cos(rad)) * rotateDirection.x * rotateDirection.y + rotateDirection.z * Mathf.Sin(rad), Mathf.Cos(rad) + (1 - Mathf.Cos(rad)) * rotateDirection.y * rotateDirection.y, (1 - Mathf.Cos(rad)) * rotateDirection.y * rotateDirection.z - rotateDirection.x * Mathf.Sin(rad), 0));
        rotateMatrix.SetRow(2, new Vector4((1 - Mathf.Cos(rad)) * rotateDirection.x * rotateDirection.z - rotateDirection.y * Mathf.Sin(rad), (1 - Mathf.Cos(rad)) * rotateDirection.y * rotateDirection.z + rotateDirection.x * Mathf.Sin(rad), Mathf.Cos(rad) + (1 - Mathf.Cos(rad)) * rotateDirection.z * rotateDirection.z, 0));
        rotateMatrix.SetRow(3, new Vector4(0, 0, 0, 1));

        var resultDirection = rotateMatrix.MultiplyVector(direction);

        return resultDirection;
    }
}
